package com.cs.rabbittest.demo;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author james
 */
public class Consumer01 {
    // 需要消费的队列的名称
    private static final String QUEUE = "helloworld";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(QUEUE, true, false, false, null);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             * 消费者接收消息调用此方法              
             * @param consumerTag 消费者的标签，在channel.basicConsume()去指定              
             * @param envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志 (收到消息失败后是否需要重新发送)              
             * @param properties              
             * @param body              
             * @throws IOException
                          */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //交换机                 
                String exchange = envelope.getExchange();
                //路由key                 
                String routingKey = envelope.getRoutingKey();
                //消息id                 
                long deliveryTag = envelope.getDeliveryTag();
                //消息内容                 
                String msg = new String(body, "utf-8");
                System.out.println("receive message.." + msg);
            }
        };
        String s = channel.basicConsume(QUEUE, false, consumer);

        System.out.println(s);
    }
}
